package com.common.utils;

import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class AesUtils {

    private static final String default_keyMode="AES";

    private static final String default_mode="AES/ECB/PKCS5Padding";

  public static String getAesRandomKey(){
//      SecureRandom是一个强随机性数适用于加密
      SecureRandom secureRandom = new SecureRandom();
      long randomKey = secureRandom.nextLong();
      return String.valueOf(randomKey);
  }

  /***
   * AES加密
   * * * */
  public static String encrypt(String content,String key){
      try{
//           创建密码器对象
          Cipher cipher = Cipher.getInstance(default_mode);

          byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);

//          初始化加密模式的密码器对象==初始化加密器准备加密
          cipher.init(Cipher.ENCRYPT_MODE,getSecretKey(key));

//          加密
          byte[] bytes = cipher.doFinal(byteContent);

          return byte2Base64(bytes);

      }catch (Exception e){
          log.error("加密失败");
      }
      return null;
  }


  public static String decrypt(String content,String key){
      try {
//          创建密码器对象
          Cipher cipher = Cipher.getInstance(default_mode);
//          初始化解密模式的密码器对象==初始化解密器准备解密
          cipher.init(Cipher.DECRYPT_MODE,getSecretKey(key));
//          解密
          byte[] bytes = cipher.doFinal(base64byte2(content));
//          将字节数组转成有效的字符串
          return new String(bytes, StandardCharsets.UTF_8);
      }catch (Exception e){
          log.error("解密失败");

      }
      return null;
  }



  /**
   * 生成加密密钥
   * * * */
  public static SecretKeySpec getSecretKey(String key){
//      生成密码器初始化所需的SecretKeySpec参数
      try {
          KeyGenerator keyGenerator = KeyGenerator.getInstance(default_keyMode);
//          指定算法名称SHA1PRNG生成key =====这种生产key的方式在不同系统上是相同的
          SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
          secureRandom.setSeed(key.getBytes());

//          AES要求密钥长度为128
          keyGenerator.init(128,secureRandom);

          SecretKey secretKey = keyGenerator.generateKey();

          return new SecretKeySpec(secretKey.getEncoded(),default_keyMode);

      }catch (Exception e){
          log.error("");

      }
      return null;
  }


  /**
   * 字节数组转base64编码
   * * * */
  public static String byte2Base64(byte[] bytes){
      Base64.Encoder encoder = Base64.getEncoder();
      return encoder.encodeToString(bytes);
  }

  public static byte[] base64byte2(String base){
      Base64.Decoder decoder = Base64.getDecoder();
      return decoder.decode(base);
  }
}
